package com.UDP;

/**
 * @ClassName ServerDemo
 * @Description UDP通信多发多收（单播、广播、、组播）
 * @Author 2214361854
 * @Date 2022/3/3 20:40
 * @Version 1.0
 */
public class ClientDemo2 {
//    public static void main(String[] args) throws Exception {
//        System.out.println("=======客户端=======");
//        //发送端对象
//        final DatagramSocket socket = new DatagramSocket(6666);
//
//
//        //发送的数据包对象
//        byte[] buffer = null;
//        final Scanner scanner = new Scanner(System.in);
//        while (true) {
//            System.out.println("发送消息：");
//            String msg = scanner.nextLine();
//            if ("exit".equals(msg)){
//                System.out.println("关闭！");
//                //释放资源
//                socket.close();
//                break;
//            }
//            buffer = msg.getBytes();
////            单播
////            DatagramPacket packet = new DatagramPacket(buffer,buffer.length, InetAddress.getLocalHost(),8888);
////            socket.send(packet);
//
////            广播，255.255.255.255
////            DatagramPacket packet2 = new DatagramPacket(buffer,buffer.length, InetAddress.getByName("255.255.255.255"),8888);
////            socket.send(packet2);
//
////            组播
//            DatagramPacket packet3 = new DatagramPacket(buffer,buffer.length, InetAddress.getByName("224.0.1.1"),8888);
//            socket.send(packet3);
//        }
//
//    }
//}
//
//class ServerDemo2{
//    public static void main(String[] args) throws Exception  {
//        System.out.println("=======服务端=======");
////      接收端对象，单播广播端口一致即可
////        final DatagramSocket socket = new DatagramSocket(8888);
//
////        组播
//        final MulticastSocket socket = new MulticastSocket(8888);
////        加入组播地址
////        socket.joinGroup(InetAddress.getByName("224.0.1.1"));
//
//        socket.joinGroup(new InetSocketAddress(InetAddress.getByName("224.0.1.1"),8888),NetworkInterface.getByInetAddress(InetAddress.getLocalHost()));
//
//        //收集的数据包对象
//        byte[] buffer = new byte[1024*64];
//        final DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
//
//        while (true) {
//            //收集数据
//            socket.receive(packet);
//
//            int len = packet.getLength();
//            String rs = new String(buffer,0,len);
//            System.out.println("收到来自："+packet.getSocketAddress()+"，对方端口是"+packet.getPort()+"的消息："+rs);
//
//        }
//        //释放资源
//        //socket.close();
//    }
}